/**
 * 1790. 仅执行一次字符串交换能否使两个字符串相等
 * https://leetcode-cn.com/problems/check-if-one-string-swap-can-make-strings-equal/
 */
public class Solutions_1790 {
    public static void main(String[] args) {
//        String s1 = "bank", s2 = "kanb";  // output: true
//        String s1 = "attack", s2 = "defend";  // output: false
//        String s1 = "kelb", s2 = "kelb";  // output: true
        String s1 = "abcd", s2 = "dcba";  // output: false

        boolean result = areAlmostEqual(s1, s2);
        System.out.println(result);
    }

    /**
     * 1.两字符串中的字符必须相同，否则无法通过交换使两字符串相同
     * 2.两字符串若相同索引上，索引不同的次数超过 2 次，则无法通过 1 次交换使两字符串相同
     *      1 次交换，可以交换两个索引上的字符
     */
    public static boolean areAlmostEqual(String s1, String s2) {
        char[] arr1 = s1.toCharArray();
        char[] arr2 = s2.toCharArray();

        int[] counts = new int[26];
        for (int i = 0; i < arr1.length; i++) {
            counts[arr1[i] - 'a'] ++;
            counts[arr2[i] - 'a'] --;
        }
        for (int i = 0; i < 26; i++) {
            if (counts[i] != 0) {
                return false;
            }
        }
        int cnt = 0;
        for (int i = 0; i < arr1.length; i++) {
            if (arr1[i] != arr2[i]) {
                cnt ++;
                if (cnt > 2) {
                    return false;
                }
            }
        }
        return true;
    }
}
